<template>
	<view class="page">
		<view class="button-group-left">
			<image @click="authLogin(1)" class="button-icon" src="https://e.zgxhcs.net/icons/grzx.png" mode=""></image>
			<image @click="authLogin(2)" class="button-icon" src="https://e.zgxhcs.net/icons/shzx.png" mode=""
				v-if="isShowShop == 1"></image>
			<image @click="authLogin(3)" class="button-icon" src="https://e.zgxhcs.net/icons/wdhb.png" mode=""
				v-if="id">
			</image>
			<image @click="authLogin(6)" class="button-icon" src="https://e.zgxhcs.net/icons/lxkf.png" mode=""
				v-if="id">
			</image>
		</view>
		<view class="button-group-right">
			<!-- <view class="userIcon-service" @click="authLogin(4)">
				所属团队
			</view> -->
			<view class="userIcon-service" @click="authLogin(5)" v-if="isShowShop == 2">
				<image class="icon" src="https://e.zgxhcs.net/icons/ddzx.png"></image>
			</view>
			<view class="userIcon-service" @click="authLogin(7)" v-if="isShowProductList == 1">
				<image class="icon" src="https://e.zgxhcs.net/icons/hdlb.png"></image>
			</view>
		</view>
		<view class="mask w-100vw h-100vh" v-if="posterShow"></view>
		<poster ref="posterRef" @closePost="closePost" v-show="posterShow"></poster>

		<!-- //授权弹框 -->
		<view class="auth_wrap" :class="isAuth ? 'show' : ''">
			<view class="mask"></view>
			<view class="auth_content">
				<view class="auth_top">
					<view class="ptitle">获取您的昵称、手机号</view>
					<view class="txt">获取用户昵称、手机号信息，主要用于完善个人资料，向用户提供更好使用体验</view>
					<!-- <view class="close" @tap="closePopup">
						<image src="/pagesPoster/static/auth/close_auth.png" mode=""></image>
					</view> -->
				</view>
				<view class="auth_ul">
					<!-- <view class="auth_li">
						<view class="tit">头像</view>
						<view class="rit">
							<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<image class="avatar" :src="avatarUrl"></image>
							</button>
						</view>
					</view> -->
					<view class="auth_li">
						<view class="tit">昵称</view>
						<view class="rit">
							<input type="nickname" class="weui-input" placeholder="请输入昵称" @blur="onNickname" />
						</view>
					</view>
					<view class="auth_li">
						<view class="tit">手机号</view>
						<view class="rit">
							<button class="avatar-wrapper" @getphonenumber="getPhoneNumber" open-type="getPhoneNumber"
								type="primary" text="获取手机号">
								<input type="text" class="weui-input" :placeholder="`${phoneNumberCode?'已获取':'请获取手机号'}`"
									disabled />
							</button>
						</view>
					</view>
				</view>
				<view class="confirm_btn" @tap.stop="handleNewLogin">保存</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		defineEmits,
		computed
	} from "vue";
	import {
		onShow,
		onLoad,
		onReady,
		onUnload,
		onHide
	} from "@dcloudio/uni-app";
	import poster from "../../components/PosterSmall.vue";
	import {
		pathToBase64
	} from "@/common/image.js"; //引入图片转base64js
	import {
		login,
		loginByPhone
	} from "/http/index.js";
	import {
		generatePosterApi
	} from "../../http";
	const props = defineProps({
		// 是否显示商户中心
		isShowShop: {
			default: 3,
			type: Number,
		}, // 是否显示商户中心// 是否显示商户中心
		isShowTeam: {
			default: 0,
			type: Number,
		}, // 是否显示商户中心
		id: {
			default: "",
			type: String,
		},
		userId: {
			default: "",
			type: String,
		},
		tenantType: {
			default: 0,
			type: Number,
		},
		// 联系客户电话
		phone: {
			default: "",
			type: String,
		},
		// 是否显示活动列表，1显示，0不显示
		isShowProductList: {
			default: 0,
			type: Number,
		},
	});
	// 生成海报
	const posterRef = ref();
	const posterShow = ref(false);
	const emit = defineEmits(["getDetails"]);
	const isAuth = ref(false); //控制授权弹框显示与隐藏
	const avatarUrl = ref(
		"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
	); //头像
	const nickname = ref(""); //昵称
	onMounted(() => {
		// 没有token ，有ID拉起登录弹出
		if (!uni.getStorageSync("AlertLogin") && props.id) {
			isAuth.value = true;
		}
	});

	// 如果头像和昵称有值，就开启获取手机号的按钮
	const phoneNumberCode = ref('');
	const getPhoneNumber = (e) => {
		if (e.detail.errMsg === 'getPhoneNumber:ok') {
			const params = {
				cloudID: e.detail.cloudID,
				code: e.detail.code,
				encryptedData: e.detail.encryptedData,
				iv: e.detail.iv
			}
			phoneNumberCode.value = params.code;
		} else {
			uni.showToast({
				title: "获取失败",
				icon: "none",
				duration: 2000,
			});
		}
	}

	const handleNewLogin = () => {
		// 授权授权时提示输入昵称
		if (!nickname.value) {
			uni.showToast({
				title: "请输入昵称",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		// 是否获取手机号code
		if (!phoneNumberCode.value) {
			uni.showToast({
				title: "请获取手机号",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		uni.login({
			success(res) {
				if (res.code) {
					uni.showLoading({
						title: "登录中...",
					});
					const params = {
						wxLoginCode: res.code,
						code: phoneNumberCode.value,
						nickName: nickname.value,
						// avatarUrl: avatarUrl.value,
					}
					loginByPhone(params).then((res) => {
							uni.$uv.toast("登录成功");
							uni.setStorageSync("AlertLogin", res.token);
							uni.setStorageSync("userInfo", res);
							uni.hideLoading();
							closePopup(); //关闭弹窗
							emit("getDetails");
						})
						.catch((err) => {
							uni.hideLoading();
							uni.showToast({
								title: "再试一次",
								duration: 1000,
								icon: "none",
							});
						});
				}
			}
		})
	}


	const authLogin = (val) => {
		console.log(props.id, "事实上事实上事实上");
		let userInfo = uni.getStorageSync("userInfo");
		//首次授权，出现授权弹框，以后退出后再登录则直接登录上去，不再出现授权弹框
		if (!userInfo) {
			isAuth.value = true;
		} else {
			isAuth.value = false;
			if (val == 1) {
				// 跳转 个人中心
				uni.navigateTo({
					url: `/pagesPoster/Leaflet/webView?path=https://ew-wx.zgxhcs.net/my/${props.userId}/${props.id}`,
				});
				// uni.$uv.route({
				// 	url: '/pages/Personal/Personal'
				// })
			} else if (val == 2) {
				// 跳转 商户中心
				uni.navigateTo({
					url: `/pagesPoster/Leaflet/webView?path=https://ew-wx.zgxhcs.net/productOrder/${props.id}`,
				});
			} else if (val == 3) {
				posterShow.value = true;
				uni.showLoading({
					title: "海报生成中...",
				});
				generatePosterApi(props.id)
					.then((res) => {
						uni.hideLoading();
						setTimeout(() => {
							posterRef.value.drawPoster(res); //在组件内drawPoster()函数编写需要绘制的内容
						}, 10);
					})
					.catch((err) => {
						uni.showToast({
							title: "绘制失败",
							duration: 2000,
							icon: "none",
						});
						uni.hideLoading();
					});
			} else if (val == 4) {
				uni.$uv.route({
					url: "/pagesPoster/Leaflet/Teams",
				});
			} else if (val == 5) {
				uni.navigateTo({
					url: `/pagesPoster/Leaflet/webView?path=https://ew-wx.zgxhcs.net/institutionOrder/${props.id}/${props.userId}`,
				});
			} else if (val == 6) {
				// 联系客服
				if (props.phone) {
					uni.makePhoneCall({
						phoneNumber: props.phone,
					});
				}
			} else if (val === 7) {
				// 跳转到活动列表
				uni.navigateTo({
					url: `/pages/ActivityCenter/ActivityCenter?tenantType=${props.tenantType}`,
				});
			}
		}
	};

	//关闭授权弹框
	const closePopup = () => {
		isAuth.value = false;
	};
	const openlogins = () => {
		isAuth.value = true;
	};

	//监听昵称变化
	const onNickname = (e) => {
		console.log('选择了昵称', e);
		nickname.value = e.detail.value;
	};

	//获取头像变化的值
	const onChooseAvatar = (e) => {
		//选择头像的临时路径
		uni.uploadFile({
			filePath: e.detail.avatarUrl,
			name: "file",
			url: `https://e.zgxhcs.net/api/file/upload`,
			success: (res) => {
				const {
					statusCode,
					data
				} = res;
				const responseData = JSON.parse(data);
				avatarUrl.value = responseData.fileUploadedFullPath;
			},
		});
	};

	const closePost = () => {
		posterShow.value = false;
	};

	//微信登录接口
	const wxgetUserProfile = (phoneParams) => {
		// 授权授权时提示输入昵称
		if (
			avatarUrl.value ==
			"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
		) {
			uni.showToast({
				title: "请选择头像",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		// 授权授权时提示输入昵称
		if (!nickname.value) {
			uni.showToast({
				title: "请输入昵称",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		uni.showLoading({
			title: "登录中...",
		});
		uni.login({
			success(res) {
				uni.hideLoading();
				if (res.code) {
					console.log("222222321", res.code);
					// 调用后端登录接口 (模拟)
					uni.showLoading({
						title: "登录中...",
					});
					loginByPhone({
							code: res.code,
							nickName: nickname.value,
							avatarUrl: avatarUrl.value,
						})
						.then((res) => {
							uni.$uv.toast("登录成功");
							uni.setStorageSync("AlertLogin", res.token);
							uni.setStorageSync("userInfo", res);
							uni.hideLoading(); // 接口调用完后 隐藏loading
							closePopup(); //关闭弹窗
							emit("getDetails");
						})
						.catch((err) => {
							uni.hideLoading();
							uni.showToast({
								title: "再试一次",
								duration: 1000,
								icon: "none",
							});
						});
				} else {
					uni.showToast({
						title: res.errMsg,
						duration: 1000,
						icon: "none",
					});
				}
			},
			fail(err) {
				uni.hideLoading();
				uni.showToast({
					title: err.error.message,
					duration: 1000,
					icon: "none",
				});
			},
		});
	};
	defineExpose({
		openlogins,
		// ... 这里列出你想暴露的属性和方法
	});
</script>

<style lang="scss">
	.mask {
		position: fixed;
		top: 0;
		z-index: 999;
		background: rgba(0, 0, 0, 0.7);
	}

	.button-group-left {
		width: 100rpx;
		min-height: 100rpx;
		display: flex;
		flex-direction: column;
		padding-left: 20rpx;
		box-sizing: border-box;
		position: fixed;
		left: 0;
		top: 40%;
		z-index: 999;

		.button-icon {
			margin-top: 20rpx;
			width: 105rpx;
			height: 105rpx;
			border-radius: 40rpx;
		}
	}

	.button-group-right {
		min-width: 100rpx;
		min-height: 100rpx;
		display: flex;
		flex-direction: column;
		position: fixed;
		right: 0;
		top: 56%;
		z-index: 999;

		.userIcon-service {
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.icon {
				width: 110rpx;
				height: 110rpx;
			}

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	//授权弹框 start
	.auth_wrap {
		position: fixed;
		width: 100%;
		bottom: -100%;
		z-index: 1000;
		transition: all 0.35s linear;

		&.show {
			bottom: 0;
			transition: all 0.35s linear;

			.mask {
				display: block;
			}
		}

		.mask {
			width: 100%;
			height: 100vh;
			position: fixed;
			background: rgba(0, 0, 0, 0.5);
			z-index: 98;
			top: 0;
			display: none;
		}

		.auth_content {
			padding: 32rpx 32rpx 72rpx 32rpx;
			position: relative;
			z-index: 99;
			background: #fff;
			border-radius: 16rpx 16rpx 0 0;

			.auth_top {
				position: relative;

				.ptitle {
					font-size: 30rpx;
					font-weight: bold;
					margin-bottom: 24rpx;
				}

				.txt {
					font-size: 26rpx;
					color: #999;
				}

				.close {
					width: 26rpx;
					height: 26rpx;
					position: absolute;
					right: 0;
					top: 0;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.auth_ul {
				margin-top: 16rpx;

				.auth_li {
					display: flex;
					align-items: center;
					border-top: solid 1px #f5f5f5;
					padding: 24rpx 0;

					&:last-child {
						border-bottom: solid 1px #f5f5f5;
					}

					.tit {
						width: 140rpx;
						font-size: 30rpx;
					}

					.rit {
						width: calc(100% - 140rpx);

						input {
							font-size: 28rpx;
							height: 72rpx;
							width: 100%;
						}

						image {
							width: 54rpx;
							height: 54rpx;
							border-radius: 50%;
						}

						button {
							width: 100%;
							height: 72rpx;
							background: #fff;
							text-align: left;
							padding: 0;

							&:after {
								border: solid 1px #fff;
							}

							// opacity: 0;
						}
					}
				}
			}

			.confirm_btn {
				width: 420rpx;
				margin: 46rpx auto 0 auto;
				background: #39b54a;
				color: #fff;
				border-radius: 8rpx;
				height: 94rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
			}
		}
	}

	//授权弹框 end

	.header {
		height: 400rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		image {
			width: 200rpx;
			height: 200rpx;
		}
	}

	.bottom {
		background: #fff;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #39b54a;
		width: calc(100% - 64rpx);
		margin: 0 32rpx;
		border: solid 1px #39b54a;
		border-radius: 40rpx;

		image {
			width: 54rpx;
			height: 54rpx;
			margin-right: 16rpx;
		}
	}
</style>